package top.ninwoo.edgecenter.register;

import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Component;
import top.ninwoo.utils.util.impl.IpUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.UUID;

/**
 * 负责将边缘服务器的信息注册到Zookeeper上
 */
@Component
public class EdgeNodeRegister implements Register {

    private final static Logger LOG = LoggerFactory.getLogger(EdgeNodeRegister.class);

    private boolean isRunning;

    @Resource
    CuratorFramework zkClient;

    @Value("${bs.cloudcenter.name}")
    private String cloudCenterName;

    @Value("${bs.edgenode.name}")
    private String edgeNodeId;

    @Value("${server.port}")
    private int port;

    @Value("${bs.edgenode.ip-prefix}")
    private String ipPrefix;

    public static String nodeId;

    @Override
    public void registerNode() {
        registerNode("random");
    }

    @Override
    public void registerNode(String nodeId) {
        if(nodeId.equals("random")) {
            nodeId = UUID.randomUUID().toString();
        }
        edgeNodeId = nodeId;
        try {
            zkClient.create()
                    .withMode(CreateMode.EPHEMERAL)
                    .forPath("/" + cloudCenterName + "/" + nodeId, (IpUtils.getHostIp(ipPrefix) + ":" + port).getBytes());
            LOG.info("临时节点【{}】已创建", nodeId);
        } catch (Exception e) {
            LOG.error("临时节点【{}】创建失败", nodeId);
            e.printStackTrace();
        }
    }

    @Override
    public String getEdgeNodeName() {
        return edgeNodeId;
    }
}
